package com.hspedu.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author DL5O
 * @version 1.0
 * 演示通过反射调用方法
 */
public class RefleAccessMethod {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        //1.得到Boss类对应的Class对象
        Class<?> bossCls = Class.forName("com.hspedu.reflection.Boss");
        Object o = bossCls.newInstance();

        //getMethod只能获得共有的
        Method hi = bossCls.getMethod("hi", String.class);//得到静态的
        hi.invoke(o, "大龙");

        //2.getDeclared可以获得所有的方法，包括私有的
        Method say = bossCls.getDeclaredMethod("say", int.class, String.class, char.class);
        say.setAccessible(true);//进行爆破
        Object s = say.invoke(o,100,"张三",'男');
        System.out.println(s.getClass());//class java.lang.String
        //因为say方法是静态的，还可以这样调用
        System.out.println(say.invoke(null,200,"张三",'男'));
        System.out.println(s);
    }
}

class Boss {
    public int age;
    private static String name;

    public Boss() {

    }

    private static String say(int n, String s, char c) {
        return n + " " + s + " " + c;
    }

    public void hi(String s) {
        System.out.println("hi " + s);
    }

    @Override
    public String toString() {
        return "Boss{" +
                "age=" + age +
                '}';
    }
}
